import { defineStore } from "pinia";
import { FavoriteApi } from "@/api/favorite-ship/favorites";

export const useFavoriteStore = defineStore("favorite", {
  state: () => ({
    // 使用 Set 存储收藏ID
    favorites: new Set<number>(),
  }),

  actions: {
    // 同步收藏状态
    async syncFavorites() {
      try {
        const res = await FavoriteApi.getFavorites();
        if (res.code === 200) {
          this.favorites = new Set(res.data.map((item: any) => item.sid));
        }
      } catch (error) {
        console.error("同步收藏失败:", error);
      }
    },

    // 添加收藏
    async addFavorite(sid: number) {
      await FavoriteApi.addFavorites({ sid });
      this.favorites.add(sid);
    },

    // 取消收藏
    async removeFavorite(sid: number) {
      await FavoriteApi.cancelFavorites({ sid });
      this.favorites.delete(sid);
    },
  },

  getters: {
    // 判断是否收藏
    isFavorite: (state) => (sid: number) => state.favorites.has(sid),
  },
});
